<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入用户名" v-model="listQuery.username">
      </el-input>
  
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>

      <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-circle-plus-outline">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

     <!-- 查询结果 -->
     <el-table size="small" :data="list" max-height="800" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column type="expand">
      <template slot-scope="props">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-form-item label="用户名">
            <span>{{ props.row.username }}</span>
          </el-form-item>
          <el-form-item label="××">
            <span></span>
          </el-form-item>
          <el-form-item label="手机号">
            <span>{{ props.row.phone }}</span>
          </el-form-item>
          <el-form-item label="邮箱">
            <span>{{ props.row.email }}</span>
          </el-form-item>

          <el-form-item label="创建时间">
            <span>{{ props.row.createTime }}</span>
          </el-form-item>

          <el-form-item label="修改时间">
            <span>{{ props.row.updateTime }}</span>
          </el-form-item>
      
        </el-form>
      </template>
    </el-table-column>
    <el-table-column align="center" type="selection" width="55" prop="id"/>

    <el-table-column align="center" min-width="100px" label="用户名" prop="username" sortable/>>

    <el-table-column align="center" min-width="100px" label="手机号码" prop="phone"/>
      
    <el-table-column align="center" min-width="100px" label="用户等级" prop="roleId"
      :filters="[{ text: '管理员', value: 2 }, { text: '普通用户', value: 1 }]" :filter-method="filterRole">
      <template slot-scope="scope">
        <el-tag >{{scope.row.roleId| formatRole}}</el-tag>
      </template>
    </el-table-column>     

    <el-table-column align="center" min-width="100px" label="状态" prop="status"
        :filters="[{ text: '可用', value: 1 }, { text: '禁用', value: 0 }]" :filter-method="filterStatus">
      <template slot-scope="scope">
         <el-tag :type="scope.row.status | statusFilter">{{scope.row.status| formatStata}}</el-tag>
      </template>
    </el-table-column>     

   <el-table-column align="center" label="操作" width="200px" class-name="small-padding fixed-width">
     <template slot-scope="scope">
      <el-button type="primary"  icon="el-icon-edit" @click="handleUpdate(scope.row)" size="mini" >编辑</el-button>
         <el-button type="danger" icon="el-icon-delete"  @click="handleDelete(scope.$index,scope.row)" size="mini">删除</el-button>
       </template>
   </el-table-column>
  </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataForm.username"></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="dataForm.phone"></el-input>
        </el-form-item>

        <el-form-item v-if="dialogStatus=='update'" label="邮箱" prop="email">
          <el-input v-model="dataForm.email"></el-input>
        </el-form-item>

        <el-form-item v-if="dialogStatus=='create'" label="密码" prop="password">
          <el-input type="password" v-model="dataForm.password" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item v-if="dialogStatus=='create'" label="确认密码" prop="checkPassword">
          <el-input type="password" v-model="dataForm.checkPassword" auto-complete="off"></el-input>
        </el-form-item>   

        <el-form-item label="用户等级" prop="roleId">
          <el-select v-model="dataForm.roleId" placeholder="请选择">
            <el-option label="普通用户" :value="1">
            </el-option>
            <el-option label="管理员" :value="2">
            </el-option>
          </el-select>
        </el-form-item>  

        <el-form-item label="状态" prop="status" v-if="dialogStatus=='update'">
          <el-select v-model="dataForm.status" placeholder="请选择">
            <el-option label="禁用" :value="0">
            </el-option>
            <el-option label="正常" :value="1">
            </el-option>
          </el-select>
        </el-form-item>            

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, createUser, updateUser, deleteUser } from '@/api/user'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'User',
  directives: {
    waves
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.dataForm.checkPassword !== '') {
          this.$refs.dataForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        username: undefined,
        sort: 'id'
      },
      dataForm: {
        id: undefined,
        username: '',
        phone: '',
        email: '',
        password: undefined,
        roleId: '',
        status:'',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        mobile: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
      }
      return statusMap[status]
    },
      // 状态显示转换
    formatStata(status) {
      const statusMap = {
        0: '禁用',
        1: '可用',  
      }
      return statusMap[status]
    },

  
     formatRole(roleId) {
      const roleMap = {
        1: '普通用户',
        2: '管理员',  
      }
      return roleMap[roleId]
    },
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data.users
        this.total = response.data.data.page.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        username: '',
        phone: '',
        password: undefined,
        checkPass: undefined,
        roleId: 1,
    
      }
    },
    filterStatus(value, row) {
      return row.status === value
    },
    filterRole(value, row) {
      return row.roleId === value
    },
    
    //添加用户界面
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //添加用户
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createUser(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) { 
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateUser(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(index,row) {
    this.dataForm = Object.assign({}, row)
     deleteUser(this.dataForm.id).then(()=>{ 
      this.list.splice(index,1)
      this.$notify({
        title: '成功',
        message: '用户删除成功！',
        type: 'success',
        duration: 2000
      })
     })
    },
    
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '手机号码', '邮箱', '用户等级', '邮箱']
        const filterVal = ['username', 'phone', 'email', 'roleId', 'status']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '用户信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
